package com.chaoxi.picturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaoxi.picturebackend.constant.UserConstant;
import com.chaoxi.picturebackend.exception.BusinessException;
import com.chaoxi.picturebackend.exception.ErrorCode;
import com.chaoxi.picturebackend.exception.ThrowUtils;
import com.chaoxi.picturebackend.mapper.UserMapper;
import com.chaoxi.picturebackend.model.dto.user.UserQueryRequest;
import com.chaoxi.picturebackend.model.entity.User;
import com.chaoxi.picturebackend.model.enums.UserRoleEnum;
import com.chaoxi.picturebackend.model.vo.LoginUserVO;
import com.chaoxi.picturebackend.model.vo.UserVO;
import com.chaoxi.picturebackend.service.UserService;
import com.github.benmanes.caffeine.cache.Cache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 用户服务实现
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;
    
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    
    @Resource(name = "userLocalCache")
    private Cache<Long, Object> userLocalCache;
    
    // 用户信息缓存前缀
    private static final String USER_CACHE_PREFIX = "user:info:";
    // 用户信息缓存过期时间（分钟）
    private static final long USER_CACHE_EXPIRE = 60 * 2;

    /**
     * 用户注册
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @return 新用户id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1.校验参数
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword, checkPassword), ErrorCode.PARAMS_ERROR,"参数不能为空");
        ThrowUtils.throwIf(userAccount.length() < 4, ErrorCode.PARAMS_ERROR,"用户账号过短");
        ThrowUtils.throwIf(userPassword.length() < 8 || checkPassword.length() < 8, ErrorCode.PARAMS_ERROR,"用户密码过短");
        ThrowUtils.throwIf(!userPassword.equals(checkPassword), ErrorCode.PARAMS_ERROR,"两次输入的密码不一致");
        // 2.检查用户账号是否重复
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(wrapper);
        ThrowUtils.throwIf(count > 0, ErrorCode.PARAMS_ERROR,"用户账号重复");
        // 3.密码加密
        String encryptedPassword = getEncryptedPassword(userPassword);
        // 4.插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptedPassword);
        user.setUserRole(UserRoleEnum.USER.getValue());
        user.setUserName("潮汐图库用户_" + userAccount);

        boolean saveResult = this.save(user);
        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR,"注册失败");
        // 主键回显
        return user.getId();
    }

    @Override
    public String getEncryptedPassword(String userPassword) {
        // 密码加密的盐
        final String SALT = "chaoxi";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    /**
     * 用户登录
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @param request 登录请求
     * @return 脱敏后的用户信息
     */
    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1. 校验参数
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword), ErrorCode.PARAMS_ERROR,"参数不能为空");
        ThrowUtils.throwIf(userAccount.length() < 4, ErrorCode.PARAMS_ERROR,"用户账号过短");
        ThrowUtils.throwIf(userPassword.length() < 8, ErrorCode.PARAMS_ERROR,"用户密码过短");
        // 2.传递的密码进行加密
        String encryptedPassword = getEncryptedPassword(userPassword);
        // 3.查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptedPassword);
        User user = userMapper.selectOne(queryWrapper);
        // 4.用户不存在
        ThrowUtils.throwIf(user == null, ErrorCode.PARAMS_ERROR,"用户不存在或密码错误");
        // 5.保存用户的登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        
        // 6.将用户信息存入缓存
        cacheUserInfo(user);

        return objToVo(user);
    }

    /**
     * 获取当前登录用户
     * @param request 请求
     * @return 当前登录用户
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 判断是否已登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if(currentUser == null || currentUser.getId() == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        
        // 先从本地缓存中获取用户信息
        User cachedUser = (User) userLocalCache.getIfPresent(currentUser.getId());
        if (cachedUser != null) {
            return cachedUser;
        }
        
        // 本地缓存未命中，从Redis缓存中获取
        String redisCacheKey = USER_CACHE_PREFIX + currentUser.getId();
        cachedUser = (User) redisTemplate.opsForValue().get(redisCacheKey);
        if (cachedUser != null) {
            // 存入本地缓存
            userLocalCache.put(currentUser.getId(), cachedUser);
            return cachedUser;
        }
        // Redis缓存未命中，从数据库查询
        currentUser = this.getById(currentUser.getId());
        if (currentUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 存入缓存（本地缓存和Redis）
        cacheUserInfo(currentUser);
        return currentUser;
    }

    /**
     * 缓存用户信息
     * @param user 用户信息
     */
    private void cacheUserInfo(User user) {
        // 存入本地缓存
        userLocalCache.put(user.getId(), user);
        
        // 存入Redis缓存
        String redisCacheKey = USER_CACHE_PREFIX + user.getId();
        redisTemplate.opsForValue().set(redisCacheKey, user, USER_CACHE_EXPIRE, TimeUnit.MINUTES);
    }

    /**
     * 更新用户信息时清除缓存
     * @param user 用户信息
     */
    public void clearUserCache(User user) {
        // 清除本地缓存
        userLocalCache.invalidate(user.getId());
        
        // 清除Redis缓存
        String redisCacheKey = USER_CACHE_PREFIX + user.getId();
        redisTemplate.delete(redisCacheKey);
    }

    /**
     * 用户登出
     * @param request 登出请求
     * @return 登出结果
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 先判断是否已经登录
        if(request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE) == null){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"未登录");
        }
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    /**
     * 获取查询包装类
     * @param userQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }


    /**
     * 获取脱敏后的用户信息
     * @param user 用户对象
     * @return 脱敏后的用户信息
     */
    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 获取脱敏后的用户列表
     * @param userList 用户列表
     * @return 脱敏后的用户列表
     */
    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }


    /**
     * 对象转为VO
     * @param user 用户对象
     * @return 脱敏后的登录用户信息
     */
    @Override
    public LoginUserVO objToVo(User user) {
        if(user == null){
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtil.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && user.getUserRole().equals(UserConstant.ADMIN_ROLE);
    }

    @Override
    public boolean changePassword(String oldPassword, String newPassword, HttpServletRequest request) {
        // 1. 校验参数
        ThrowUtils.throwIf(StringUtils.isAnyBlank(oldPassword, newPassword),
                ErrorCode.PARAMS_ERROR, "参数为空");
        
        // 2. 获取当前登录用户
        User currentUser = getLoginUser(request);
        
        // 3. 校验旧密码是否正确
        String encryptedOldPassword = getEncryptedPassword(oldPassword);
        ThrowUtils.throwIf(!encryptedOldPassword.equals(currentUser.getUserPassword()),
                ErrorCode.PARAMS_ERROR, "旧密码错误");
        
        // 4. 校验新密码与旧密码不相同
        String encryptedNewPassword = getEncryptedPassword(newPassword);
        ThrowUtils.throwIf(encryptedNewPassword.equals(currentUser.getUserPassword()),
                ErrorCode.PARAMS_ERROR, "新密码不能与旧密码相同");
        
        // 5. 更新密码
        User updateUser = new User();
        updateUser.setId(currentUser.getId());
        updateUser.setUserPassword(encryptedNewPassword);
        
        boolean result = this.updateById(updateUser);
        // 如果更新成功，清除缓存
        if (result) {
            clearUserCache(currentUser);
        }
        
        return result;
    }
}